package com.bmicpd.gzh.util;

import org.openqa.selenium.OutputType;
import org.openqa.selenium.phantomjs.PhantomJSDriver;
import org.openqa.selenium.phantomjs.PhantomJSDriverService;
import org.openqa.selenium.remote.DesiredCapabilities;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;

/**
 * @author ytree
 */
public class PhantomJsUtils {

    /**
     * 创建无界面浏览器对象
     * @param phantomJsPath phantomJs安装路径
     * @return PhantomJSDriver
     */
    public static PhantomJSDriver getPhantomJsDriver(String phantomJsPath){

        // 对phantomjs进行配置，初始化
        // 必要参数
        DesiredCapabilities dcaps = new DesiredCapabilities();
        //ssl证书支持
        dcaps.setCapability("acceptSslCerts", true);
        // css搜索支持
        dcaps.setCapability("cssSelectorsEnabled", true);
        //js支持
        dcaps.setJavascriptEnabled(true);
        //驱动支持
        dcaps.setCapability(PhantomJSDriverService.PHANTOMJS_EXECUTABLE_PATH_PROPERTY,
                phantomJsPath);
        //创建无界面浏览器对象
        return new PhantomJSDriver(dcaps);
    }

    /**
     * 渲染html为图片
     * @param htmlUrl 被渲染的url
     * @param phantomJSDriver phantomJs 驱动
     * @param formatName 转换后图片格式后缀名
     * @param imagePath 转换后图片保存路径
     * @throws IOException 图片存储时有可能出现的异常
     * @throws InterruptedException thread 延时可能出现的中断异常
     */
    public static void renderer2Image(String htmlUrl, PhantomJSDriver phantomJSDriver,
                                      String formatName, String imagePath) throws IOException, InterruptedException {

        // 启动无界面浏览器
        phantomJSDriver.get(htmlUrl);

        // 进行右侧滚动条滚动，等待图片加载
        for(int scrollSite = 0; scrollSite <= 20000; scrollSite += 100) {

            String js = "var q=document.body.scrollTop=" + scrollSite;
            phantomJSDriver.executeScript(js);
            Thread.sleep(500);
        }

        // 将加载完成的html生成图片
        File file = phantomJSDriver.getScreenshotAs(OutputType.FILE);
        BufferedImage bufferedImage = ImageIO.read(file);
        ImageIO.write(bufferedImage, formatName, new File(imagePath));

    }

}
